package su.choco.queuing.controller;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import su.choco.queuing.domain.Item;
import su.choco.queuing.domain.Queue;
import su.choco.queuing.service.I.QueueService;

import java.util.List;

@RestController
@RequestMapping("/queues")
public class QueueController {
    @Autowired
    QueueService queueService;

    @ApiOperation(value = "查询所有队列", notes = "返回系统当前所有已经创建的队列")
    @RequestMapping(path = "/", method = RequestMethod.GET)
    public List<Queue> getQueue() {
        return queueService.getAll();
    }

    @ApiOperation(value = "创建队列", notes = "根据Queue对象创建队列")
    @ApiImplicitParam(name = "queue", value = "队列详细实体queue", required = true, dataType = "Queue")
    @RequestMapping(path = "/", method = RequestMethod.POST)
    public String createQueue(@ModelAttribute Queue queue) {
        queueService.add(queue);
        return "success";
    }

    @ApiOperation(value = "查询指定队列", notes = "按照指定的名字返回队列信息")
    @RequestMapping(path = "/{name}", method = RequestMethod.GET)
    public Queue getQueue(@PathVariable String name) {
        return queueService.get(name);
    }

    @ApiOperation(value = "更新队列信息", notes = "更新队列信息，需要指定队列名称")
    @ApiImplicitParam(name = "queue", value = "队列详细实体queue", required = true, dataType = "Queue")
    @RequestMapping(path = "/{name}", method = RequestMethod.POST)
    public String updateQueue(@PathVariable String name, @ModelAttribute Queue queue) {
        if(name.equals(queue.getName())){
            queueService.update(queue);
            return "success";
        }else{
            return "fail";
        }
    }

    @ApiOperation(value = "入队", notes = "往指定队列添加一个等待对象")
    @ApiImplicitParam(name = "item", value = "等待对象实体item", required = true, dataType = "Item")
    @RequestMapping(path = "/{name}/enqueue", method = RequestMethod.POST)
    public String enqueue(@PathVariable String name, @ModelAttribute Item item) {
        Queue queue = queueService.get(name);

        if(queue == null){
            return "fail";
        }

        if(queue.enqueue(item)){
            return "success";
        }else{
            return "fail";
        }
    }

    @ApiOperation(value = "出队", notes = "返回并删除队列首部")
    @RequestMapping(path = "/{name}/dequeue", method = RequestMethod.POST)
    public Item dequeue(@PathVariable String name) {
        Queue queue = queueService.get(name);

        if(queue == null){
            return null;
        }else{
            return queue.dequeue();
        }
    }
/*
    @RequestMapping({
            "/status",
            "/index"})
    public String index() {
        return "Queuing Service OK.";
    }
    */
}
